package hot;

import java.util.Arrays;

/**
 * @author lakersUp
 * @Classname   下一个排列
 * @Description     较小数尽量靠右, 较大数尽量小
 * @Date 2022/3/9 10:06
 * @Version 1.0
 */
public class Hot31nextPermutation {
    public void nextPermutation(int[] nums) {
        int n=nums.length;
        int i=n-2;
        while (i>=0 && nums[i]>=nums[i+1]){
            i--;
        }
        if(i>=0){
            int j=n-1;
            while(j>=0 && nums[j]<=nums[i]){
                j--;
            }
            swap(nums,i,j);
        }
        // i+1后变为升序
        reverse(nums,i+1);
    }

    public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public void reverse(int[] nums, int start) {
        int left = start, right = nums.length - 1;
        while (left < right) {
            swap(nums, left, right);
            left++;
            right--;
        }
    }
}
